package org.tinygame.herostory.codec;

import com.google.protobuf.GeneratedMessageV3;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandler;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import org.tinygame.herostory.msg.GameMsgProtocol;

public class GameMsgEncoder extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if(null == msg || !(msg instanceof GeneratedMessageV3)){
            super.write(ctx,msg,promise);
            return;
        }

        int msgCode = GameMsgCoder.getMsgCodeByMsgClazz(msg.getClass());

        if(msgCode <= -1){
            System.out.println("msgCode小于-1，无法识别消息：" + msg.getClass().getName());
            return;
        }

        byte [] byteArr = ((GeneratedMessageV3) msg).toByteArray();

        ByteBuf byteBuf = ctx.alloc().buffer();//申请一个byteBuf对象
        byteBuf.writeShort((short)0);//写出一个长度
        byteBuf.writeShort((short)msgCode);//写出一个编号
        byteBuf.writeBytes(byteArr);//写出消息体

        BinaryWebSocketFrame frame = new BinaryWebSocketFrame(byteBuf);
        super.write(ctx,frame,promise);//执行父类方法
    }
}
